 /*
  | SI4732   | Function   | DAC      | ESP LOLIN32 WEMOS (GPIO)              |
  |-----------| ----------|----------|---------------------------------------|  
  | pin  1    |  DFS/WS   | LRCK     |  WordSelect / GPIO25        5          |
  | pin 16    |  DIO/SD   | DIN      |  SerialData / GPIO32        7          |
  | pin  2    |  DCLK/SCK | BSK      |  ContinuousSerialClock)  / GPIO33   4  |    
*/
#include <driver/i2s.h>
#include <soc/i2s_reg.h>

#define Bit_Clock_BCLK 4
#define Word_Select_WS 5
#define Serial_Data_SD 7

// Define input buffer length
#define bufferLen 64


int16_t sBuffer[bufferLen];

const i2s_config_t i2s_config = {
  .mode = i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX),
  .sample_rate = 48000,
  .bits_per_sample = i2s_bits_per_sample_t(16),  // Resolution: More bits better quality
  .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
  .communication_format = i2s_comm_format_t(I2S_COMM_FORMAT_STAND_I2S),
  .intr_alloc_flags = 0,
  .dma_buf_count = 8,
  .dma_buf_len = bufferLen,
  .use_apll = false
};

const i2s_pin_config_t pin_config = {
  .bck_io_num = Bit_Clock_BCLK,
  .ws_io_num = Word_Select_WS,
  .data_out_num = -1,
  .data_in_num = Serial_Data_SD
};

void setup() {
  Serial.begin(115200);
  // put your setup code here, to run once:
  i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);
  i2s_set_pin(I2S_NUM_0, &pin_config);
  i2s_set_clk(I2S_NUM_0, 48000, I2S_BITS_PER_SAMPLE_16BIT, I2S_CHANNEL_MONO);
  i2s_start(I2S_NUM_0);

  Serial.print("\nI2S setup is done!. Now you can open the Serial Plot Monitor.");
  delay(2000);


}

void loop() {
  // put your main code here, to run repeatedly:
// Get I2S data and place in data buffer
    size_t bytesIn = 0;
    esp_err_t result = i2s_read(I2S_NUM_0, &sBuffer, bufferLen, &bytesIn, portMAX_DELAY);

    if (result == ESP_OK) {
      // Read I2S data buffer
      int16_t samples_read = bytesIn / 8;
      if (samples_read > 0) {
        float mean = 0;
        for (int16_t i = 0; i < samples_read; ++i) {
          mean += (sBuffer[i]);
        }

        // Average the data reading
        mean /= samples_read;

        // Print to serial plotter
        Serial.println(mean);
      }
    }
}
